#include "cppTutorStackUsingLinkedList.h"

#include <iostream>

Stack :: Stack ()
{
    stackPtr = NULL;
}

// what is going to happen to our stack once our stack os going to end
Stack :: ~Stack()
{
    item* p1;
    item* p2;

    p1 = stackPtr;  // we either have a stack that exists, this will point p1 to the top of stack, if the stack is not present ot will point to the NULL

    while (p1 != NULL)  // we are at top of the stack, and move till down
    {
        p2 = p1;        //  p2 is actually deleting the element and it will point the top of the stack
        p1 = p1->prev;  // make p1 point to the item below the p1
        p2->prev = NULL;// it will seperate the item from the stack
        delete p2;
    }
    delete p1;
}

void Stack ::Push (string name, int value)
{
    item* n = new item; // create a new item, n pooin to the new item now
    n->name = name;     // put the passed name in n
    n->value = value;   // put the passed value in n

    if (stackPtr == NULL)   // there is no item then make the n as the top of the item
    {
        stackPtr = n;       // first item in the stack
        stackPtr->prev = NULL;  // no prev element presnent as this is the first element
    }
    else    // if there is a stack present
    {
        n->prev = stackPtr; // stackPtr will point to the top of the stack
        stackPtr = n;       // stackPtr is now at the new top of the stack
    }

}

void Stack :: ReadItem (item* r)
{
    cout << "--------------------\n" << endl;
    cout << "name\t:" << r->name << endl;
    cout << "value\t:" << r->value << endl;
    cout << "--------------------\n" << endl;
}

void Stack :: Pop ()
{
    if (stackPtr == NULL)
    {
        cout << "stack is empty" << endl;
    }
    else    // if there is a stack
    {
        item* p = stackPtr; // make a item pointer and point it to where the stackPtr is pointing to
        ReadItem (p);   // call the readitem function tp print the content
        stackPtr = stackPtr->prev;  //stackPtr is now  pointing to the second to the top item, 
        p->prev = NULL; // now we can delete the top item, it is actually seperating the item
        delete p;
    }
}

void Stack :: Print ()
{
    item* p = stackPtr;
    while (p != NULL)
    {
        ReadItem (p);
        p = p->prev;
    }
}

